/*
 * Copyright 2010 - 2011, The PLDesktop Development Team
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

#include "physicalpagemanager.h"

#include <stddef.h>
#include <machine/pc/memory/staticmemhandler.h>
#include <machine/pc/memory/memmanager.h>
#include <machine/machine.h>

PhysicalPageManager::PhysicalPageManager() : m_memSize(0) {
}

void PhysicalPageManager::init() {
	m_memMapSize = m_memSize / PAGE_SIZE;
	m_memMapMapped = 0;
	m_memUsedMapLength = (m_memMapSize / 32) + 1;
	m_memUsedMap = new uint32_t[m_memUsedMapLength];
	for(uint32_t i = 0 ; i < m_memUsedMapLength ; i++) {
		m_memUsedMap[i] = 0;
	}
}

void PhysicalPageManager::activate() {
	// The memory is page aligned from the virtual memory manager startup.
	setUsed(0, ((PLStaticMemHandler *)PLMachine::instance().kernelMemManger()->memhander())->currentMem());
}

void PhysicalPageManager::setMemSize(uint32_t newMemSize) {
	if(m_memSize == 0) {
		m_memSize = newMemSize;
	}
}

void PhysicalPageManager::setUsed(uint32_t startAdress, uint32_t length) {
	uint32_t startMap = startAdress / PAGE_SIZE;
	uint32_t endMap   = (startAdress + length) / PAGE_SIZE;
	if(endMap * PAGE_SIZE < startAdress + length) {
		endMap++;
	}
	for(uint32_t i = startMap ; i < endMap ; i++) {
		mmap_set(i);
		m_memMapMapped++;
	}
}

uint32_t PhysicalPageManager::findNextFree() {
	for(uint32_t i = 0 ; i < m_memUsedMapLength ; i++) {
		if(m_memUsedMap[i] != 0xffffffff) {
			for(uint32_t j = 0 ; j < 32 ; j++) {
				uint32_t bit = 1 << j;
				if(!(m_memUsedMap[i] & bit)) {
					return i * 32 + j;
				}
			}
		}
	}
	return 0;
}
